// 认证状态管理工具
import store from '@/store'

/**
 * 获取当前页面上下文（前台或管理后台）
 */
export function getCurrentContext() {
  const path = window.location.pathname
  return path.includes('/admin') ? 'admin' : 'frontend'
}

/**
 * 检查是否有有效的登录状态
 */
export function hasValidAuth(context = null) {
  if (!context) {
    context = getCurrentContext()
  }
  
  let token, userInfo
  
  if (context === 'admin') {
    token = localStorage.getItem('adminToken')
    userInfo = localStorage.getItem('adminUserInfo')
  } else {
    token = localStorage.getItem('userToken')
    userInfo = localStorage.getItem('userUserInfo')
  }
  
  // 向后兼容
  if (!token && !userInfo) {
    token = localStorage.getItem('token')
    userInfo = localStorage.getItem('userInfo')
  }
  
  return !!(token && userInfo)
}

/**
 * 尝试恢复用户登录状态
 */
export async function restoreAuthState(context = null) {
  if (!context) {
    context = getCurrentContext()
  }
  
  try {
    // 如果已经有登录状态，不需要重复恢复
    if (store.getters.getLoginStatus) {
      const userInfo = store.getters.getUserInfo
      if (context === 'admin' && (userInfo.role === 'ADMIN' || userInfo.userRole === 'ADMIN')) {
        return { success: true, message: '管理员状态已存在' }
      } else if (context === 'frontend' && (userInfo.role === 'USER' || userInfo.userRole === 'USER')) {
        return { success: true, message: '用户状态已存在' }
      }
    }
    
    // 检查是否有存储的认证信息
    if (!hasValidAuth(context)) {
      return { success: false, message: '没有找到有效的认证信息' }
    }
    
    // 尝试从localStorage恢复状态
    const result = await store.dispatch('initializeUser', context)
    
    if (result.success) {
      // 验证恢复的状态是否有效
      if (store.getters.getLoginStatus) {
        try {
          const validateResult = await store.dispatch('autoValidateUser', context)
          if (validateResult.success) {
            console.log(`${context === 'admin' ? '管理员' : '用户'}状态恢复并验证成功`)
            return { success: true, message: '登录状态恢复成功' }
          } else {
            console.warn('状态恢复后验证失败:', validateResult.message)
            return { success: false, message: '登录状态已过期' }
          }
        } catch (error) {
          console.error('验证恢复状态时出错:', error)
          return { success: false, message: '验证登录状态失败' }
        }
      } else {
        return { success: false, message: '状态恢复失败' }
      }
    } else {
      return result
    }
  } catch (error) {
    console.error('恢复认证状态时出错:', error)
    return { success: false, message: '恢复认证状态失败' }
  }
}

/**
 * 清除指定上下文的认证状态
 */
export function clearAuthState(context = null) {
  if (!context) {
    context = getCurrentContext()
  }
  
  store.commit('CLEAR_USER_INFO')
  
  if (context === 'admin') {
    localStorage.removeItem('adminToken')
    localStorage.removeItem('adminUserInfo')
  } else {
    localStorage.removeItem('userToken')
    localStorage.removeItem('userUserInfo')
  }
  
  // 向后兼容：只有在没有其他角色登录时才清除通用存储
  const hasOtherAuth = context === 'admin' 
    ? (localStorage.getItem('userToken') || localStorage.getItem('userUserInfo'))
    : (localStorage.getItem('adminToken') || localStorage.getItem('adminUserInfo'))
  
  if (!hasOtherAuth) {
    localStorage.removeItem('token')
    localStorage.removeItem('userInfo')
  }
}

/**
 * 页面刷新时的状态恢复处理
 */
export async function handlePageRefresh() {
  const context = getCurrentContext()
  
  console.log(`页面刷新，当前上下文: ${context}`)
  
  // 如果当前已有登录状态，检查是否匹配上下文
  if (store.getters.getLoginStatus) {
    const userInfo = store.getters.getUserInfo
    const isAdmin = userInfo.role === 'ADMIN' || userInfo.userRole === 'ADMIN'
    
    if ((context === 'admin' && isAdmin) || (context === 'frontend' && !isAdmin)) {
      console.log('当前登录状态与页面上下文匹配，无需重新恢复')
      return { success: true, message: '状态匹配' }
    } else {
      console.log('当前登录状态与页面上下文不匹配，需要重新恢复')
      store.commit('CLEAR_USER_INFO')
    }
  }
  
  // 尝试恢复对应上下文的状态
  return await restoreAuthState(context)
} 